package com.qyhl.module_practice.newhome;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.flyco.tablayout.SlidingTabLayout;
import com.gyf.immersionbar.ImmersionBar;
import com.luck.picture.lib.permissions.RxPermissions;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qinanyu.bannerview.holder.SimpleHolder;
import com.qinanyu.bannerview.holder.SimpleHolderCreator;
import com.qinanyu.bannerview.view.SimpleBannerView;
import com.qyhl.module_practice.R;
import com.qyhl.module_practice.R2;
import com.qyhl.module_practice.newhome.fragment.act.PracticeHomeActFragment;
import com.qyhl.module_practice.newhome.fragment.news.PracticeHomeNewsFragment;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.SpanUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.glide.GlideOptionsUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.constant.HomeStyle;
import com.qyhl.webtv.commonlib.entity.civilized.PracticeAcitivityBean;
import com.qyhl.webtv.commonlib.entity.civilized.PracticeHomeMenuBean;
import com.qyhl.webtv.commonlib.entity.civilized.PracticeHomeMenuListBean;
import com.qyhl.webtv.commonlib.entity.civilized.PracticeIsVolunteerBean;
import com.qyhl.webtv.commonlib.entity.civilized.PracticeNewHomeBean;
import com.qyhl.webtv.commonlib.entity.news.GlobalNewsBean;
import com.qyhl.webtv.commonlib.entity.news.NewsBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.ItemSkipUtils;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.PersonalViewPager;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;

public class PracticeNewHomeFragment extends BaseFragment implements PracticeNewHomeContract.PracticeNewHomeView {
    @BindView(R2.id.title)
    TextView title;
    @BindView(R2.id.title_layout)
    RelativeLayout titleLayout;
    @BindView(R2.id.navigation_rv)
    RecyclerView navigationRv;
    @BindView(R2.id.tabLayout)
    SlidingTabLayout tabLayout;
    @BindView(R2.id.viewPager)
    PersonalViewPager viewPager;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refreshLayout;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.team_num)
    TextView teamNum;
    @BindView(R2.id.act_num)
    TextView actNum;
    @BindView(R2.id.vol_num)
    TextView volNum;
    @BindView(R2.id.time_num)
    TextView timeNum;
    @BindView(R2.id.count_layout)
    LinearLayout countLayout;
    @BindView(R2.id.banner)
    SimpleBannerView<String> mBanner;
    @BindView(R2.id.banner_one)
    SimpleBannerView<String> mBanner1;
    @BindView(R2.id.navigation_layout)
    CardView navigationLayout;
    @BindView(R2.id.love_enter_btn)
    ImageButton loveEnterBtn;
    @BindView(R2.id.brand_enter_btn)
    ImageButton brandEnterBtn;
    @BindView(R2.id.map_enter_btn)
    ImageButton mapEnterBtn;
    @BindView(R2.id.bottom_layout)
    LinearLayout bottomLayout;
    @BindView(R2.id.pager_layout)
    LinearLayout pagerLayout;
    @BindView(R2.id.street_enter_btn)
    ImageButton streetEnterBtn;
    @BindView(R2.id.service_enter_btn)
    ImageButton serviceEnterBtn;
    @BindView(R2.id.flipper_layout)
    CardView flipperLayout;
    @BindView(R2.id.view_flipper)
    ViewFlipper viewFlipper;
    @BindView(R2.id.top_layout)
    RelativeLayout topLayout;
    @BindView(R2.id.header_bg)
    RelativeLayout headerBg;
    @BindView(R2.id.vol_num_layout)
    LinearLayout volNumLayout;
    @BindView(R2.id.act_num_layout)
    LinearLayout actNumLayout;
    @BindView(R2.id.back_btn)
    ImageView backBtn;

    private String instId;

    private String titleName;

    private boolean isBottom;

    private String userName;

    private int volStatus = 0;

    private String volId = "0";

    private boolean isRefresh = false;

    private boolean isTop = false;

    public void setTop(boolean top) {
        isTop = top;
    }

    private PracticeNewHomePresenter mPresenter;

    public void setTitleName(String titleName) {
        this.titleName = titleName;
    }

    public void setBottom(boolean bottom) {
        isBottom = bottom;
    }

    public void setInstId(String instId) {
        this.instId = instId;
    }


    private List<PracticeHomeMenuBean> navigationListBean = new ArrayList<>();

    private CommonAdapter navigationAdapter;

    private RxPermissions rxPermissions;

    private PracticeHomeMenuListBean mBean;

    private List<GlobalNewsBean> indexList;

    private List<String> bannerList = new ArrayList<>();

    private String mCatalogId;


    private HomeStyle homeStyle = HomeStyle.NORMAL;

    public void setHomeStyle(HomeStyle homeStyle) {
        this.homeStyle = homeStyle;
    }

    @SuppressLint("InflateParams")
    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.practice_fragment_home_new, null);
    }

    public static PracticeNewHomeFragment newInstance(String institutionId, String titleName, boolean isBottom, boolean isTop) {
        PracticeNewHomeFragment fragment = new PracticeNewHomeFragment();
        fragment.setInstId(institutionId);
        fragment.setTitleName(titleName);
        fragment.setBottom(isBottom);
        HomeStyle style;
        if (CommonUtils.getInstance().getSite() == 140 || CommonUtils.getInstance().getSite() == 127) {
            style = HomeStyle.QIXIA;
        } else {
            style = HomeStyle.NORMAL;
        }
        fragment.setHomeStyle(style);
        fragment.setTop(isTop);
        return fragment;
    }

    public static PracticeNewHomeFragment newInstance(String institutionId, String titleName, boolean isBottom, HomeStyle homeStyle, boolean isTop) {
        PracticeNewHomeFragment fragment = new PracticeNewHomeFragment();
        fragment.setInstId(institutionId);
        fragment.setTitleName(titleName);
        fragment.setBottom(isBottom);
        fragment.setHomeStyle(homeStyle);
        fragment.setTop(isTop);
        return fragment;
    }

    @Override
    public void initImmersionBar() {
        if (!isTop) {
            super.initImmersionBar();
            ImmersionBar.with(this)
                    .statusBarDarkFont(true, 0.2f)
                    .titleBar(titleLayout)
                    .init();
        }
    }

    @Override
    protected void setListener() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                mPresenter.getMenu();
            }
        });

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                isRefresh = true;
                mPresenter.getIsVolunteer(userName);
                mPresenter.getMenu();
            }
        });

        navigationAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @SuppressLint("CheckResult")
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                switch (navigationListBean.get(position).getTypeId()) {
                    case 1: {
                        Bundle bundle = new Bundle();
                        bundle.putString("id", instId);
                        bundle.putInt("status", volStatus);
                        bundle.putString("volId", StringUtils.isEmpty(volId) ? "" : volId);
                        bundle.putSerializable("bean", navigationListBean.get(position));
                        bundle.putInt("style", navigationListBean.get(position).getMenuStyle());
                        bundle.putString("title", navigationListBean.get(position).getMenuName());
                        RouterManager.router(ARouterPathConstant.PRACTICE_SUB_STREET, bundle);
                    }


                    break;
                    case 2://成为志愿者
                        CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                            @Override
                            public void login(boolean isLogin) {
                                if (isLogin) {
                                    if (volStatus == 1) {
                                        showToast("您已经是志愿者！");
                                    } else if (volStatus == 2) {
                                        showToast("您志愿者资格审核中！");
                                    } else {
                                        Bundle bundle = new Bundle();
                                        bundle.putString("id", "");
                                        bundle.putString("title", navigationListBean.get(position).getMenuName());
                                        bundle.putString("instId", instId);
                                        bundle.putBoolean("isVolunteer", true);
                                        RouterManager.router(ARouterPathConstant.PRACTICE_VOLUNTEER_SIGN, bundle);

                                    }
                                } else {
                                    showToast("尚未登录或登录已失效！");
                                    RouterManager.routerLogin(getContext(), 0);
                                }
                            }

                            @Override
                            public void error(String s) {

                            }
                        });
                        break;
                    case 3://志愿者
                    {
                        boolean isVolunteer = volStatus == 1 || volStatus == 2;
                        Bundle bundle = new Bundle();
                        bundle.putString("id", instId);
                        bundle.putBoolean("isVolunteer", isVolunteer);
                        bundle.putString("title", navigationListBean.get(position).getMenuName());
                        RouterManager.router(ARouterPathConstant.PRACTICE_VOLUNTEER, bundle);
                    }
                    break;
                    case 4://志愿团队
                        if (volStatus == 1) {
                            Bundle bundle = new Bundle();
                            bundle.putString("volId", volId);
                            bundle.putInt("status", volStatus);
                            bundle.putString("instId", instId);
                            bundle.putString("title", navigationListBean.get(position).getMenuName());
                            RouterManager.router(ARouterPathConstant.PRACTICE_TEAM_LIST, bundle);
                        } else {
                            Bundle bundle = new Bundle();
                            bundle.putString("volId", "0");
                            bundle.putInt("status", volStatus);
                            bundle.putString("instId", instId);
                            bundle.putString("title", navigationListBean.get(position).getMenuName());
                            RouterManager.router(ARouterPathConstant.PRACTICE_TEAM_LIST, bundle);
                        }
                        break;
                    case 5://服务项目
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("streetId", instId);
                        bundle.putString("type", "0,3");
                        bundle.putString("id", instId);
                        bundle.putString("title", navigationListBean.get(position).getMenuName());
                        RouterManager.router(ARouterPathConstant.PRACTICE_ACTIVITY_LIST, bundle);
                    }
                    break;
                    case 6://点单

                        CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                            @Override
                            public void login(boolean isLogin) {
                                if (isLogin) {
                                    if (volStatus == 1) {
                                        Bundle bundle = new Bundle();
                                        bundle.putString("id", volId);
                                        bundle.putString("instId", instId);
                                        bundle.putString("title", navigationListBean.get(position).getMenuName());
                                        bundle.putString("userName", userName);
                                        RouterManager.router(ARouterPathConstant.PRACTICE_ORDER, bundle);
                                    } else {
                                        Bundle bundle = new Bundle();
                                        bundle.putString("id", "0");
                                        bundle.putString("instId", instId);
                                        bundle.putString("title", navigationListBean.get(position).getMenuName());
                                        bundle.putString("userName", userName);
                                        RouterManager.router(ARouterPathConstant.PRACTICE_ORDER, bundle);
                                    }
                                } else {
                                    showToast("尚未登录或登录已失效！");
                                    RouterManager.routerLogin(getContext(), 0);
                                }
                            }

                            @Override
                            public void error(String s) {

                            }
                        });

                        break;
                    case 7://秀文明
                    {
                        CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                            @Override
                            public void login(boolean isLogin) {
                                if (isLogin) {
                                    Bundle bundle = new Bundle();
                                    bundle.putString("id", navigationListBean.get(position).getCatalogId());
                                    bundle.putString("title", navigationListBean.get(position).getMenuName());
                                    RouterManager.router(ARouterPathConstant.PRACTICE_CIRCLE, bundle);
                                } else {
                                    showToast("尚未登录或登录已失效！");
                                    RouterManager.routerLogin(getContext(), 0);
                                }
                            }

                            @Override
                            public void error(String s) {

                            }
                        });
                    }
                    break;
                    case 8://实践直播
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("title", navigationListBean.get(position).getMenuName());
                        bundle.putString("type", "1");
                        RouterManager.router(ARouterPathConstant.TELETEXT_LIST, bundle);
                    }
                    break;
                    case 9://全部直播
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("title", navigationListBean.get(position).getMenuName());
                        bundle.putString("type", "0");
                        RouterManager.router(ARouterPathConstant.TELETEXT_LIST, bundle);
                    }

                    break;
                    case 10://服务上传
                        CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                            @Override
                            public void login(boolean isLogin) {
                                if (isLogin) {
                                    if (volStatus == 1) {
                                        Bundle bundle = new Bundle();
                                        bundle.putString("volId", volId);
                                        bundle.putString("title", navigationListBean.get(position).getMenuName());
                                        bundle.putString("userName", userName);
                                        bundle.putString("userName", userName);
                                        RouterManager.router(ARouterPathConstant.PRACTICE_APPLY, bundle);
                                    } else if (volStatus == 2) {
                                        showToast("您的志愿者资格审核中，请耐心等待~", 4);
                                    } else {
                                        showToast("请先成为志愿者", 4);
                                    }

                                } else {
                                    showToast("尚未登录或登录已失效！");
                                    RouterManager.routerLogin(getContext(), 0);
                                }
                            }

                            @Override
                            public void error(String s) {

                            }
                        });
                        break;
                    case 11://扫码计时

                        CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                            @Override
                            public void login(boolean isLogin) {
                                if (isLogin) {
                                    if (volStatus == 1) {
                                        Bundle bundle = new Bundle();
                                        bundle.putString("volId", volId);
                                        bundle.putString("title", navigationListBean.get(position).getMenuName());
                                        bundle.putBoolean("isHome", true);
                                        RouterManager.router(ARouterPathConstant.PRACTICE_QR_CODE, bundle);
                                    } else if (volStatus == 2) {
                                        showToast("志愿者资格审核中！", 4);
                                    } else {
                                        showToast("请先成为志愿者！", 4);
                                    }
                                } else {
                                    showToast("尚未登录或登录已失效！");
                                    RouterManager.routerLogin(getContext(), 0);
                                }
                            }

                            @Override
                            public void error(String s) {

                            }
                        });
                        break;
                    case 12://排行榜
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("instId", instId);
                        bundle.putString("title", navigationListBean.get(position).getMenuName());
                        bundle.putInt("id", Integer.parseInt(volId));
                        RouterManager.router(ARouterPathConstant.PRACTICE_RANK, bundle);
                    }
                    break;
                    case 13://积分银行
                        CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                            @Override
                            public void login(boolean isLogin) {
                                if (isLogin) {
                                    Bundle bundle = new Bundle();
                                    bundle.putString("id", volId);
                                    bundle.putString("title", navigationListBean.get(position).getMenuName());
                                    bundle.putString("userName", userName);
                                    RouterManager.router(ARouterPathConstant.PRACTICE_SCORE_SHOP, bundle);
                                } else {
                                    showToast("尚未登录或登录已失效！");
                                    RouterManager.routerLogin(getContext(), 0);
                                }
                            }

                            @Override
                            public void error(String s) {

                            }
                        });
                        break;
                    case 14://我要学知识
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("id", navigationListBean.get(position).getCatalogId());
                        bundle.putString("title", navigationListBean.get(position).getMenuName());
                        bundle.putBoolean("isNew", false);
                        RouterManager.router(ARouterPathConstant.PRACTICE_STUDY, bundle);
                    }
                    break;
                    case 15://个人中心
                        CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                            @Override
                            public void login(boolean isLogin) {
                                if (isLogin) {

                                    Bundle bundle = new Bundle();
                                    bundle.putString("title", navigationListBean.get(position).getMenuName());
                                    bundle.putString("id", volId);
                                    bundle.putString("instId", instId);
                                    bundle.putInt("status", volStatus);
                                    bundle.putString("userName", userName);
                                    RouterManager.router(ARouterPathConstant.PRACTICE_CENTER, bundle);
                                } else {
                                    showToast("尚未登录或登录已失效！");
                                    RouterManager.routerLogin(getContext(), 0);
                                }
                            }

                            @Override
                            public void error(String s) {

                            }
                        });
                        break;
                    case 16://爱心对接
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("id", instId);
                        bundle.putString("title", "爱心对接");
                        bundle.putString("type", "1,2");
                        bundle.putInt("fromType", 0);
                        RouterManager.router(ARouterPathConstant.PRACTICE_ACTIVITY_LIST, bundle);

                    }
                    break;
                    case 17://品牌志愿
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("title", navigationListBean.get(position).getMenuName());
                        RouterManager.router(ARouterPathConstant.PRACTICE_BRAND_LIST, bundle);
                    }
                    break;
                    case 18://文明地图
                    {
                        rxPermissions
                                .request(Manifest.permission.ACCESS_FINE_LOCATION)
                                .subscribe(granted -> {
                                    if (granted) {
                                        Bundle bundle = new Bundle();
                                        bundle.putString("instId", instId);
                                        RouterManager.router(ARouterPathConstant.PRACTICE_MAP, bundle);
                                    }
                                });
                    }
                    break;
                    case 19://捐赠
                        RouterManager.router(ARouterPathConstant.PRACTICE_DONATE_LIST);
                        break;
                    case 20: {
                        Bundle bundle = new Bundle();
                        bundle.putString("title", navigationListBean.get(position).getMenuName());
                        bundle.putString("url", navigationListBean.get(position).getUrl());
                        bundle.putBoolean("hasShare", false);
                        RouterManager.router(ARouterPathConstant.ADV, bundle);
                    }
                    break;
                    case 28: {
                        Bundle bundle = new Bundle();
                        bundle.putString("title", navigationListBean.get(position).getMenuName());
                        bundle.putString("id", navigationListBean.get(position).getCatalogId());
                        bundle.putBoolean("isNew", true);
                        RouterManager.router(ARouterPathConstant.PRACTICE_STUDY, bundle);
                    }
                    break;
                    case 30: {
                        Bundle bundle = new Bundle();
                        bundle.putString("volId", volId);
                        bundle.putInt("volStatus", volStatus);
                        bundle.putString("instId", instId);
                        bundle.putString("title", navigationListBean.get(position).getMenuName());
                        RouterManager.router(ARouterPathConstant.PRACTICE_SERVICE, bundle);
                    }
                    default:
                        break;
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(final int position) {
                // 切换到当前页面，重置高度
                viewPager.requestLayout();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    protected void create() {
        mPresenter = new PracticeNewHomePresenter(this);
        rxPermissions = new RxPermissions(Objects.requireNonNull(getActivity()));
        loadMask.setStatus(LoadingLayout.Loading);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setRefreshHeader(new MaterialHeader(Objects.requireNonNull(getContext())));
        refreshLayout.setRefreshFooter(new ClassicsFooter(getContext()));
        BusFactory.getBus().register(this);
        userName = CommonUtils.getInstance().getUserName();

        if (isBottom) {
            backBtn.setVisibility(View.GONE);
        } else {
            backBtn.setVisibility(View.VISIBLE);
        }

        if (isTop) {
            titleLayout.setVisibility(View.GONE);
        } else {
            titleLayout.setVisibility(View.VISIBLE);
        }

        title.setText(titleName);

        if (homeStyle == HomeStyle.NORMAL) {
            topLayout.setVisibility(View.GONE);
            mBanner.setVisibility(View.VISIBLE);

        } else if (homeStyle == HomeStyle.QIXIA) {
            topLayout.setVisibility(View.GONE);
            mBanner.setVisibility(View.VISIBLE);

            RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            param.addRule(RelativeLayout.ALIGN_PARENT_START);
            tabLayout.setLayoutParams(param);
            tabLayout.setIndicatorHeight(0);
        } else {
            if (homeStyle == HomeStyle.TAIAN) {
                headerBg.setBackgroundResource(R.drawable.practice_home_head_bg);
            } else {
                headerBg.setBackgroundResource(R.color.global_base);
            }
            topLayout.setVisibility(View.VISIBLE);
            mBanner.setVisibility(View.GONE);
            countLayout.setVisibility(View.GONE);
        }


        //设置布局管理器

        if (homeStyle == HomeStyle.QIXIA) {
            navigationRv.setLayoutManager(new GridLayoutManager(getContext(), 4));

            navigationRv.setAdapter(navigationAdapter = new CommonAdapter<PracticeHomeMenuBean>(getContext(), R.layout.practice_item_navigation, navigationListBean) {
                @Override
                protected void convert(ViewHolder holder, PracticeHomeMenuBean bean, int position) {
                    holder.setText(R.id.title, bean.getMenuName());

                    ImageView cover = holder.getView(R.id.cover);
                    Glide.with(PracticeNewHomeFragment.this)
                            .load(bean.getMenuImg())
                            .apply(new RequestOptions().error(R.drawable.cover_large_default).placeholder(R.drawable.cover_large_default))
                            .into(cover);
                }
            });
        } else {
            navigationRv.setLayoutManager(new GridLayoutManager(getContext(), 5));

            navigationRv.setAdapter(navigationAdapter = new CommonAdapter<PracticeHomeMenuBean>(getContext(), R.layout.practice_item_navigation, navigationListBean) {
                @Override
                protected void convert(ViewHolder holder, PracticeHomeMenuBean bean, int position) {
                    holder.setText(R.id.title, bean.getMenuName());

                    ImageView cover = holder.getView(R.id.cover);
                    Glide.with(PracticeNewHomeFragment.this)
                            .load(bean.getMenuImg())
                            .apply(new RequestOptions().error(R.drawable.cover_large_default).placeholder(R.drawable.cover_large_default))
                            .into(cover);
                }
            });
        }


        mPresenter.getIsVolunteer(userName);
        mPresenter.getMenu();
    }

    @Override
    protected void onFirstVisible() {

    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void onHide() {

    }


    @OnClick({R2.id.back_btn, R2.id.love_enter_btn, R2.id.brand_enter_btn, R2.id.map_enter_btn, R2.id.more})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.back_btn) {
            BusFactory.getBus().post(new Event.finishActivity());
        } else if (id == R.id.love_enter_btn) {
            Bundle bundle = new Bundle();
            bundle.putString("id", instId);
            bundle.putString("title", "爱心对接");
            bundle.putString("type", "1,2");
            bundle.putInt("fromType", 0);
            RouterManager.router(ARouterPathConstant.PRACTICE_ACTIVITY_LIST, bundle);
        } else if (id == R.id.brand_enter_btn) {
            RouterManager.router(ARouterPathConstant.PRACTICE_BRAND_LIST);
        } else if (id == R.id.map_enter_btn) {
            Bundle bundle = new Bundle();
            bundle.putString("instId", instId);
            RouterManager.router(ARouterPathConstant.PRACTICE_MAP, bundle);
        } else if (id == R.id.more) {
            if (mBean != null && mBean.getInformation() != null && mBean.getInformation().size() > 0) {
                if (tabLayout.getCurrentTab() == 0) {
                    if (mBean.getInformation().get(0).getTypeId() == 25) {
                        Bundle bundle = new Bundle();
                        bundle.putString("title", mBean.getInformation().get(0).getMenuName());
                        bundle.putString("id", mBean.getInformation().get(0).getCatalogId());
                        RouterManager.router(ARouterPathConstant.NEWS_LIST, bundle);
                    } else {
                        Bundle bundle = new Bundle();
                        bundle.putString("type", "0,3");
                        bundle.putString("id", instId);
                        bundle.putString("title", mBean.getInformation().get(0).getMenuName());
                        RouterManager.router(ARouterPathConstant.PRACTICE_ACTIVITY_LIST, bundle);
                    }

                } else {
                    if (mBean.getInformation().get(1).getTypeId() == 25) {
                        Bundle bundle = new Bundle();
                        bundle.putString("title", mBean.getInformation().get(1).getMenuName());
                        bundle.putString("id", mBean.getInformation().get(1).getCatalogId());
                        RouterManager.router(ARouterPathConstant.NEWS_LIST, bundle);
                    } else {
                        Bundle bundle = new Bundle();
                        bundle.putString("type", "0,3");
                        bundle.putString("id", instId);
                        bundle.putString("title", mBean.getInformation().get(1).getMenuName());
                        RouterManager.router(ARouterPathConstant.PRACTICE_ACTIVITY_LIST, bundle);
                    }
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMessage(Event.LoginMessage event) {
        if (event != null) {
            userName = CommonUtils.getInstance().getUserName();
            mPresenter.getIsVolunteer(userName);
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refresh(Event.PracticeActRefresh event) {
        if (event != null) {
            userName = CommonUtils.getInstance().getUserName();
            mPresenter.getIsVolunteer(userName);
        }
    }

    @Override
    public void setMenuList(PracticeHomeMenuListBean bean) {
        mBean = bean;
        if (bean.getMenu() != null && bean.getMenu().size() > 0) {
            navigationLayout.setVisibility(View.VISIBLE);
            navigationListBean.clear();
            navigationListBean.addAll(bean.getMenu());
            navigationAdapter.notifyDataSetChanged();
        } else {
            navigationLayout.setVisibility(View.GONE);
        }

        if (bean.getBottom() != null && bean.getBottom().size() > 0) {
            bottomLayout.setVisibility(View.VISIBLE);
            for (int i = 0; i < bean.getBottom().size(); i++) {
                if (bean.getBottom().get(i).getTypeId() == 17) {
                    brandEnterBtn.setVisibility(View.VISIBLE);
                    Glide.with(PracticeNewHomeFragment.this)
                            .load(bean.getBottom().get(i).getMenuImg())
                            .apply(GlideOptionsUtils.getInstance().getOptions(R.drawable.cover_large_default, R.drawable.cover_large_default))
                            .into(brandEnterBtn);
                } else if (bean.getBottom().get(i).getTypeId() == 18) {
                    mapEnterBtn.setVisibility(View.VISIBLE);
                    Glide.with(PracticeNewHomeFragment.this)
                            .load(bean.getBottom().get(i).getMenuImg())
                            .apply(GlideOptionsUtils.getInstance().getOptions(R.drawable.cover_large_default, R.drawable.cover_large_default))
                            .into(mapEnterBtn);
                }
            }
        } else {
            bottomLayout.setVisibility(View.GONE);
        }

        if (bean.getMiddle() != null && bean.getMiddle().size() > 0) {
            for (int i = 0; i < bean.getMiddle().size(); i++) {
                PracticeHomeMenuBean menuBean = bean.getMiddle().get(i);
                switch (menuBean.getTypeId()) {
                    case 1:
                        streetEnterBtn.setVisibility(View.VISIBLE);
                        Glide.with(PracticeNewHomeFragment.this)
                                .load(menuBean.getMenuImg())
                                .apply(GlideOptionsUtils.getInstance().getOptions(R.drawable.cover_large_default, R.drawable.cover_large_default))
                                .into(streetEnterBtn);
                        streetEnterBtn.setOnClickListener(view -> {
                            Bundle bundle = new Bundle();
                            bundle.putString("id", instId);
                            bundle.putInt("status", volStatus);
                            bundle.putString("volId", StringUtils.isEmpty(volId) ? "" : volId);
                            bundle.putInt("style", menuBean.getMenuStyle());
                            bundle.putString("title", menuBean.getMenuName());
                            bundle.putSerializable("bean", menuBean);
                            RouterManager.router(ARouterPathConstant.PRACTICE_SUB_STREET, bundle);
                        });
                        break;
                    case 5:
                        serviceEnterBtn.setVisibility(View.VISIBLE);
                        Glide.with(PracticeNewHomeFragment.this)
                                .load(menuBean.getMenuImg())
                                .apply(GlideOptionsUtils.getInstance().getOptions(R.drawable.cover_large_default, R.drawable.cover_large_default))
                                .into(serviceEnterBtn);
                        serviceEnterBtn.setOnClickListener(view -> {
                            Bundle bundle = new Bundle();
                            bundle.putString("streetId", instId);
                            bundle.putString("type", "0,3");
                            bundle.putString("id", instId);
                            bundle.putString("title", menuBean.getMenuName());
                            RouterManager.router(ARouterPathConstant.PRACTICE_ACTIVITY_LIST, bundle);
                        });
                        break;
                    case 16:
                        loveEnterBtn.setVisibility(View.VISIBLE);
                        Glide.with(PracticeNewHomeFragment.this)
                                .load(menuBean.getMenuImg())
                                .apply(GlideOptionsUtils.getInstance().getOptions(R.drawable.cover_large_default, R.drawable.cover_large_default))
                                .into(loveEnterBtn);

                        break;
                }
            }
        }

        if (bean.getTop() != null && bean.getTop().size() > 0) {
            flipperLayout.setVisibility(View.GONE);
            countLayout.setVisibility(View.GONE);
            for (int i = 0; i < bean.getTop().size(); i++) {

                switch (bean.getTop().get(i).getTypeId()) {
                    case 24://统计
                        if (homeStyle == HomeStyle.NORMAL || homeStyle == HomeStyle.QIXIA) {
                            countLayout.setVisibility(View.VISIBLE);
                        }
                        break;
                    case 23://滚动新闻
                        flipperLayout.setVisibility(View.VISIBLE);
                        break;
                    case 22://顶部轮播
                        bannerList.clear();
                        for (int j = 0; j < bean.getTop().get(i).getAdditional().size(); j++) {
                            bannerList.add(bean.getTop().get(i).getAdditional().get(j).getUrl());
                        }

                        //当只有一张轮播图时
                        if (bannerList.size() == 1) {
                            if (homeStyle == HomeStyle.NORMAL || homeStyle == HomeStyle.QIXIA) {
                                mBanner.setCanLoop(false);//停止轮播
                            } else {
                                mBanner1.setCanLoop(false);//停止轮播
                            }
                        }

                        if (homeStyle == HomeStyle.NORMAL || homeStyle == HomeStyle.QIXIA) {
                            mBanner.setPages(new SimpleHolderCreator() {
                                @Override
                                public BannerImageHolderView createHolder() {
                                    return new BannerImageHolderView();
                                }
                            }, bannerList)
                                    .hideBannerText(true)
                                    .hideBannerTitle(true)
                                    .startTurning(3000);
                        } else {
                            mBanner1.setPages(new SimpleHolderCreator() {
                                @Override
                                public BannerImageHolderView createHolder() {
                                    return new BannerImageHolderView();
                                }
                            }, bannerList)
                                    .hideBannerText(true)
                                    .hideBannerTitle(true)
                                    .startTurning(3000);
                        }

                        break;
                }
            }
        }
        mPresenter.getData(instId, userName);
    }


    @SuppressLint("SetTextI18n")
    @Override
    public void setData(PracticeNewHomeBean bean) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        refreshLayout.finishRefresh();

        //配置中间栏目
        if (mBean.getInformation() != null && mBean.getInformation().size() > 0) {
            if (isRefresh) {
                if (bean.getRecAct() != null && bean.getRecAct().size() > 6) {
                    List<PracticeAcitivityBean> list = new ArrayList<>();
                    for (int i = 0; i < 6; i++) {
                        list.add(bean.getRecAct().get(i));
                    }
                    BusFactory.getBus().post(new Event.PracticeHomeActRefresh(list));
                } else {
                    BusFactory.getBus().post(new Event.PracticeHomeActRefresh(bean.getRecAct()));
                }

                BusFactory.getBus().post(new Event.PracticeHomeNewsRefresh(StringUtils.isEmpty(mCatalogId) ? "" : mCatalogId));
            } else {
                pagerLayout.setVisibility(View.VISIBLE);
                List<String> nameList = new ArrayList<>();
                List<Fragment> fragments = new ArrayList<>();
                for (int i = 0; i < mBean.getInformation().size(); i++) {
                    nameList.add(mBean.getInformation().get(i).getMenuName());
                    switch (mBean.getInformation().get(i).getTypeId()) {
                        case 25:
                            mCatalogId = mBean.getInformation().get(i).getCatalogId();
                            fragments.add(PracticeHomeNewsFragment.newInstance(mCatalogId));
                            break;
                        case 26:
                            if (bean.getRecAct() != null && bean.getRecAct().size() > 6) {
                                List<PracticeAcitivityBean> list = new ArrayList<>();
                                for (int j = 0; j < 6; j++) {
                                    list.add(bean.getRecAct().get(j));
                                }
                                fragments.add(PracticeHomeActFragment.newInstance(list, instId));
                            } else {
                                fragments.add(PracticeHomeActFragment.newInstance(bean.getRecAct(), instId));
                            }
                            break;
                        default:
                            fragments.add(new TestFragment());
                            break;
                    }
                }
                viewPager.setAdapter(new Adapter(getChildFragmentManager(), fragments, nameList));
                tabLayout.setViewPager(viewPager);
            }
        } else {
            pagerLayout.setVisibility(View.GONE);
        }

        if (homeStyle == HomeStyle.NORMAL || homeStyle == HomeStyle.QIXIA) {
            String teamTip = "组织团体(个)";
            if (homeStyle == HomeStyle.QIXIA) {
                teamTip = "志愿团体(个)";
            }
            Typeface fontFace = Typeface.createFromAsset(getContext().getAssets(),
                    "fonts/ReductoCondSSK.ttf");
            SpanUtils spanUtils = new SpanUtils(getContext());
            spanUtils.append(bean.getOrgCount() + "\n").setFontSize(23, true).setTypeface(fontFace)
                    .append(teamTip).setFontSize(11, true);
            teamNum.setText(spanUtils.create());

            SpanUtils spanUtil2 = new SpanUtils(getContext());
            spanUtil2.append(bean.getActCount() + "\n").setFontSize(23, true).setTypeface(fontFace)
                    .append("服务项目(个)").setFontSize(11, true);
            actNum.setText(spanUtil2.create());

            SpanUtils spanUtil3 = new SpanUtils(getContext());
            spanUtil3.append(bean.getVolCount() + "\n").setFontSize(23, true).setTypeface(fontFace)
                    .append("志愿者(人)").setFontSize(11, true);
            volNum.setText(spanUtil3.create());

            if (CommonUtils.getInstance().getSite() == 140 || CommonUtils.getInstance().getSite() == 127) {
                SpanUtils spanUtil4 = new SpanUtils(getContext());
                spanUtil4.append(bean.getInsCount() + "\n").setFontSize(23, true).setTypeface(fontFace)
                        .append("文明实践组织(个)").setFontSize(11, true);
                timeNum.setText(spanUtil4.create());
            } else {
                SpanUtils spanUtil4 = new SpanUtils(getContext());
                spanUtil4.append(DateUtils.PracticeServiceTimeFormat(Long.parseLong(bean.getSerTime())) + "\n").setFontSize(23, true).setTypeface(fontFace)
                        .append("服务时长(小时)").setFontSize(11, true);
                timeNum.setText(spanUtil4.create());
            }

        } else {
            volNumLayout.removeAllViewsInLayout();
            actNumLayout.removeAllViewsInLayout();
            int volNum = bean.getVolCount();
            int actNum = bean.getActCount();
            for (int i = 0; i < String.valueOf(bean.getVolCount()).length(); i++) {
                TextView textView = new TextView(getActivity());
                textView.setBackgroundResource(R.color.practice_80per_white);
                textView.setTextColor(getResources().getColor(R.color.global_black_lv1));
                textView.setPadding(3, 0, 3, 0);
                textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
                textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));

                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                layoutParams.setMargins(StringUtils.dip2px(getContext(), 3), 0, 0, 0);
                textView.setLayoutParams(layoutParams);

                textView.setText(volNum % 10 + "");
                volNum = volNum / 10;
                volNumLayout.addView(textView, 0);
            }

            for (int i = 0; i < String.valueOf(bean.getActCount()).length(); i++) {
                TextView textView = new TextView(getActivity());
                textView.setBackgroundResource(R.color.practice_80per_black);
                textView.setTextColor(getResources().getColor(R.color.white));
                textView.setPadding(3, 0, 3, 0);
                textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
                textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));

                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                layoutParams.setMargins(StringUtils.dip2px(getContext(), 3), 0, 0, 0);
                textView.setLayoutParams(layoutParams);

                textView.setText(actNum % 10 + "");
                actNum = actNum / 10;
                actNumLayout.addView(textView, 0);
            }
        }

        if (bean.getNews() != null && bean.getNews().size() > 0) {
            setNews(bean.getNews());
            viewFlipper.removeAllViews();
            for (int i = 0; i < indexList.size(); i++) {
                View view = Objects.requireNonNull(getActivity()).getLayoutInflater().inflate(R.layout.practice_item_viewflipper, null);
                TextView title = view.findViewById(R.id.title);
                title.setText(indexList.get(i).getTitle());
                int finalI = i;
                view.setOnClickListener(v -> ItemSkipUtils.getInstance().itemSkip(indexList.get(finalI), getContext(), view));
                viewFlipper.addView(view);
            }

            viewFlipper.setFlipInterval(2000);
            viewFlipper.startFlipping();
        }
    }

    @Override
    public void setError(String msg) {
        loadMask.setStatus(LoadingLayout.Error);
        refreshLayout.finishRefresh();
        loadMask.setReloadButtonText("点击重试~");
        if (!NetUtil.isNetworkAvalible(Objects.requireNonNull(getContext()))) {
            loadMask.setErrorImage(R.drawable.error_network);
            loadMask.setErrorText("网络异常，请检查您的网络！");
        } else if (msg.contains("暂无")) {
            loadMask.setErrorImage(R.drawable.empty_content);
            loadMask.setErrorText(msg);
        } else {
            loadMask.setErrorImage(R.drawable.error_content);
            loadMask.setErrorText(msg);
        }
    }

    @Override
    public void setIsVolunteer(PracticeIsVolunteerBean bean) {
        if (bean != null) {
            if (bean.getVolId() == 0) {
                volStatus = 0;
            } else {
                volId = bean.getVolId() + "";
                switch (bean.getStatus()) {
                    case "PASS":
                        volStatus = 1;
                        break;
                    case "NOT_VERIFY":
                        volStatus = 2;
                        break;
                    case "NOT_PASS":
                        volStatus = 3;
                        break;
                    case "DEL":
                        volStatus = 4;
                        break;
                }
            }
        } else {
            volStatus = 0;
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        BusFactory.getBus().unregister(this);
    }


    class Adapter extends FragmentPagerAdapter {
        private List<Fragment> fragmentList;
        private List<String> names;

        Adapter(FragmentManager fm, List<Fragment> fragmentList, List<String> names) {
            super(fm);
            this.fragmentList = fragmentList;
            this.names = names;
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentList.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return names.get(position);
        }
    }

    /*
     * 设置新闻
     */
    private void setNews(List<NewsBean> beanList) {
        indexList = new ArrayList<>();

        //数据类型转换
        for (int i = 0; i < beanList.size(); i++) {
            NewsBean bean = beanList.get(i);
            boolean hasPicture = StringUtils.isPictureSuccess(bean.getLogo());
            String type = "", pOne = "", pTwo = "", pThree = "";
            int style = 0;
            switch (bean.getType()) {
                case "1"://普通新闻
                    type = "1";
                    switch (bean.getPluralPicsFlag()) {
                        case 0:
                            style = bean.getCommonStyle();
                            break;
                        case 1://三图
                            style = 4;
                            break;
                        case 2:
                            style = 3;
                            break;
                        default:
                            style = bean.getCommonStyle();
                            break;
                    }
                    break;
                case "2"://图片新闻
                    type = "2";
                    break;
                case "3"://直播
                    type = "9";
                    break;
                case "4"://标题新闻
                    type = "8";
                    break;
                case "5"://视频新闻
                    type = "3";
                    style = bean.getVideoStyle();
                    break;
                case "8"://互动直播
                    bean.setID(bean.getRoomId());//将roomId设置成通用Id
                    type = "5";
                    break;
                case "101"://抓取新闻
                    type = "10";
                    break;
                default:
                    break;
            }
            indexList.add(new GlobalNewsBean(bean.getTitle(), bean.getID(), bean.getRedirectURL(), bean.getLogo(), style, bean.getPublishDate(), type, Integer.parseInt(bean.getHitCount()), bean.getSource(), bean.getCatalogID(), hasPicture, pOne, pTwo, pThree, bean.getLivetype(), bean.getCommentCount()));
        }
    }

    /**
     * 顶部轮播holder
     */
    class BannerImageHolderView implements SimpleHolder<String> {
        private RoundedImageView imageView;

        @Override
        public View createView(Context context) {
            imageView = new RoundedImageView(context);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageView.setCornerRadius(12.0f);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, int position, String data) {
            Glide.with(context)
                    .load(data)
                    .apply(new RequestOptions().error(R.drawable.cover_large_default).placeholder(R.drawable.cover_large_default))
                    .into(imageView);
        }
    }


}
